<style lang="scss" scoped>
  .status-0, .status-2{ color: #ee0a24; }
  .status-1{ color: #ff976a; }
  .status-3{ color: #07c160; }
  .infos-box{
    .avatar-upload{
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .avatar{
      width: 2.44rem;
      height: 2.44rem;
      background-color: #fff;
      border-radius: 50%;
      margin: .2rem auto;
      position: relative;
      > img{
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
      .edit{
        position: absolute;
        right: 0;
        top: .4rem;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .tips{
      margin: .2rem .6rem;
      font-size: .24rem;
      color: #666;
      line-height: 1.5;
    }
    .submit{
      margin: .2rem;
    }
  }

  .modal-box{
    padding: .2rem .4rem;
    input,textarea{
      padding: .2rem;
      outline: none;
      border: 1px solid #e9e9e9;
      background-color: #fff;
      border-radius: 4px;
      width: 100%;
      min-height: .64rem;
    }
  }
</style>

<template>
  <div class="container hasNav">
    <van-nav-bar title="个人资料" left-arrow left-text="返回" @click-left="$router.back()" fixed />
    <div class="infos-box">
      <div class="avatar-upload">
        <van-uploader :after-read="afterAvatarRead" :max-size="5 * 1024 * 1024">
          <div class="avatar">
            <img :src="form.avatar" v-if="form.avatar">
            <div class="edit">
              <van-icon name="edit" color="#179AFE" size="24" />
            </div>
          </div>
        </van-uploader>
      </div>
      <div class="cells">
        <van-cell title="我的认证" to="/user/certAuth" is-link >
          <div :class="`status-${userInfo.user.authStatus}`">
            {{getAuthStatusName(userInfo.user.authStatus)}}
          </div>
        </van-cell>
        <van-cell
            title="姓名"
            :value="form.username"
            @click="showModalEvent(0)"
            :is-link="!isAuthed" />
        <van-cell
            title="性别"
            :value="genderName"
            @click="showGenderEvent"
            :is-link="!isAuthed" />
        <van-cell
            title="出生日期"
            :value="`${!!form.birthday ? $moment(form.birthday).format('YYYY年MM月DD日') : '未填写'}`"
            @click="showBirthEvent"
            :is-link="!isAuthed" />
        <van-cell
            title="简介"
            :value="form.introduction"
            @click="showModalEvent(1)"
            is-link />
      </div>

      <div class="tips">
        请完善您的基本信息，系统将于3个工作日内审核处理.
      </div>

      <div class="submit">
        <van-button block type="default" color="#179AFE" @click="onSubmit">保存</van-button>
      </div>
    </div>

    <!-- 填写姓名、简介 -->
    <van-dialog
        v-model="showModal"
        :title="`请填写${modalTitle}`"
        @confirm="handleModalConfirm"
        @open="handleModalOpen"
        @close="handleModalClose"
        show-cancel-button>
      <div class="modal-box">
        <template v-if="modalType === 0">
          <input type="text" v-model="modalValue" maxlength="20" placeholder="请填写姓名">
        </template>
        <template v-if="modalType === 1">
          <textarea v-model="modalValue" cols="30" rows="10" maxlength="1000" placeholder="请填写简介，最多1000字。"></textarea>
        </template>
      </div>
    </van-dialog>
    <!-- 选择性别 -->
    <van-action-sheet
        v-model="showGender"
        :actions="genders"
        cancel-text="取消"
        close-on-click-action
        @select="onGenderSelect" />

    <!-- 选择出生年月日 -->
    <van-popup v-model="showBirth" position="bottom">
      <van-datetime-picker
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onBirthConfirm"
          @cancel="showBirth = false"
          v-model="currentDate"
          :formatter="dateFormat"
      />
    </van-popup>
    <Loading :isShow="loading"></Loading>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Loading from '@/components/Loading';
import { saveUserAvatar, saveUserInfos, getUserInfo } from "../../api/user";

function isNull(val) {
  return val === '' || !val
}

export default {
  name: 'UserInfos',
  components: {
    Loading,
  },
  data() {
    return {
      loading: true,
      showModal: false,
      showGender: false,
      showBirth: false,
      genders: [
        { name: '男', value: 1 },
        { name: '女', value: 2 }
      ],
      modalType: 0, // 0 姓名 1 简介
      currentDate: new Date(),
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2050, 0, 1),
      form: {
        avatar: null,
        username: null,
        gender: 1,
        birthday: null,
        introduction: null
      },
      genderName: '',
      modalValue: ''
    };
  },
  mounted() {
    this.getDetail();
  },
  computed: {
    ...mapGetters(['userInfo']),
    modalTitle() {
      return this.modalType === 1 ? '简介' : '姓名'
    },
    isAuthed() {
      return this.userInfo.user.authStatus === 3
    }
  },
  methods: {
    async getDetail() {
      try {
        this.loading = true;
        const { code, msg, data } = await getUserInfo();
        if (code == 200) {
          this.form.avatar = data.headPic
          this.form.username = !isNull(data.username) ? data.username : ''
          this.form.gender = +data.gender
          this.form.genderName = this.genderName = +data.gender === 1 ? '男' : +data.gender === 2 ? '女' : '未知'
          this.form.birthday = !isNull(data.birthday) ? data.birthday : ''
          this.form.introduction = !isNull(data.introduction) ? data.introduction : ''
          this.currentDate = !isNull(data.birthday) ? new Date(data.birthday) : new Date()
          let userInfo = JSON.parse(JSON.stringify(this.userInfo))
          userInfo.user.authStatus = data.authStatus;
          this.$store.commit('setUserInfo', userInfo);
        } else {
          this.$toast(msg);
        }
        this.$nextTick(() => {
          this.loading = false;
        });
      } catch (error) {
        console.log(error);
        this.loading = false;
      }
    },
    showModalEvent(index) {
      if(this.isAuthed && index === 0) {
        return this.$toast('您已通过认证，若要修改姓名、性别、生日，请联系系统助手!')
      }
      this.showModal = true;
      this.modalType = index;
    },
    showGenderEvent() {
      if(this.isAuthed) return this.$toast('您已通过认证，若要修改姓名、性别、生日，请联系系统助手!');
      this.showGender = true;
    },
    showBirthEvent() {
      if(this.isAuthed) return this.$toast('您已通过认证，若要修改姓名、性别、生日，请联系系统助手!');
      this.showBirth = true;
    },
    onGenderSelect(item) {
      this.form.gender = item.value;
      this.form.genderName = item.name
      this.genderName = item.name
    },
    onBirthConfirm(date) {
      this.showBirth = false;
      this.form.birthday = this.$moment(date).format('YYYY-MM-DD')
    },
    dateFormat(type, val) {
      if (type === 'year') {
        return val + '年';
      }
      if (type === 'month') {
        return val + '月';
      }
      if (type === 'day') {
        return val + '日';
      }
      return val;
    },
    async afterAvatarRead(file) {
      let formData = new FormData();
      formData.append('file', file.file)
      const { code, msg, headPic } = await saveUserAvatar(formData)
      if(code == 200) {
        this.form.avatar = headPic
        let userInfo = JSON.parse(JSON.stringify(this.userInfo))
        userInfo.user.headPic = headPic
        this.$store.commit('setUserInfo', userInfo)
        this.$toast('修改头像成功!')
      } else {
        this.$toast(msg)
      }
    },
    handleModalConfirm() {
      let keyName = ['username', 'introduction']
      if(isNull(this.modalValue)) {
        this.$toast('内容不能为空')
        return
      }
      this.form[keyName[this.modalType]] = this.modalValue;
    },
    handleModalOpen() {
      let keyName = ['username', 'introduction']
      this.modalValue = this.form[keyName[this.modalType]]
    },
    handleModalClose() {
      this.modalValue = '';
    },
    async onSubmit() {
      let formData = new FormData();
      if(isNull(this.form.username) || isNull(this.form.gender) || isNull(this.form.birthday)) {
        this.$toast('必须填写姓名、性别和生日')
        return
      }
      formData.append('username', this.form.username);
      formData.append('gender', this.form.gender);
      formData.append('birthday', this.form.birthday);
      formData.append('introduction', this.form.introduction);
      const { code, msg } = await saveUserInfos(formData)
      if(code == 200) {
        let userInfo = JSON.parse(JSON.stringify(this.userInfo))
        userInfo.user.username = this.form.username
        userInfo.user.gender = this.form.gender
        userInfo.user.birthday = this.form.birthday
        userInfo.user.introduction = this.form.introduction
        this.$store.commit('setUserInfo', userInfo)
        this.$toast('保存成功')
      } else {
        this.$toast(msg)
      }
    },
    getAuthStatusName(status) {
      return status === 1 ? '认证中' : status === 2 ? '认证失败' : status === 3 ? '认证成功' : '未认证'
    }
  }
};
</script>
